package su.jet.irc.client.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import su.jet.common.irc.domain.Message;
import su.jet.common.irc.domain.User;
import su.jet.common.irc.protocol.Session;

public class MessageHandler {
	
	private User sender;

	private BufferedReader input;
	
	public MessageHandler(User sender) {
		this.sender = sender;
		input = new BufferedReader(new InputStreamReader(System.in));
	}
	
	public User getSender() {
		return sender;
	}

	public Message readFromConsole() {
		Message message;
		User receiver;
		String textFromClient;
		try {
			textFromClient = input.readLine();
			String [] argsFromClient = textFromClient.split("->");
			if (argsFromClient.length > 1) {
				receiver = new User (argsFromClient[0].trim());
				message = new Message (argsFromClient[1].trim(), sender, receiver) ;
			} else {
				receiver = null;
				message = new Message(argsFromClient[0].trim(), sender, receiver);
			}
			return message;
		} catch (IOException e) {
			System.out.println("Input failed!");
			//e.printStackTrace();
		}
		return null;	
	}

	public String textFromMessage(Message message) {
		String text;
		if (message.getReceiver() != null)
			text = message.getSender().getNickName() + " (privately) for " + message.getReceiver().getNickName() + " -> " + message.getText();
		else
			text = message.getSender().getNickName() + " -> " + message.getText();
		return text;
	}
	
	public void sendTextToReaderApplication (Message message, Session session) {
		String outputString = textFromMessage(message);
		try {
			session.sendObject(outputString);
		} catch (IOException e) {
			System.out.println("Error! Reader console closed!");
			//e.printStackTrace();
		}
		
	}
	
	public void sendTextToReaderApplication (String text, Session session) {
		try {
			session.sendObject(text);
		} catch (IOException e) {
			System.out.println("Error! Reader console closed!");
			//e.printStackTrace();
		}
	}
	
	public void setInput(BufferedReader input) {
		this.input = input;
	}
	
}
